# -*- coding: utf-8 -*-
"""
Created on Mon Nov 15 10:49:45 2021

@author: Dylan.Gao
"""

import paho.mqtt.client as mqtt
import sys,getopt

# 监听的数据类型
_types = []

# 排除监听的数据类型
_xtypes = []

# 监听的模型类型
_modules = []

# 排除监听的模型类型
_xmodules = []

# 监听的设备列表
_devs = []

# 排除监听的设备列表
_xdevs = []

_broker_address = "172.16.2.24"
_broker_port = 1883
_broker_keepalive = 10

_topics = ['+/get/request/database/+','database/get/response/+/+',
           '+/action/request/database/+','database/action/response/+/+',
           '+/set/request/database/+','database/set/response/+/+',
           '+/notify/event/database/+/+',
           'database/report/notify/broadcast/+/+',
           '+/report/notify/broadcast/+']

def on_connect( client, userData, flags, rc ):
    print('连接服务器成功:%s:%s'%(_broker_address,_broker_port))
    for topic in _topics:
        print('订阅主题:%s'%topic)
        client.subscribe(topic)

def on_disconn( client, userData, rc ):
    print(u'%s:%s连接断开'%(_broker_address,_broker_port))

def on_message( client, userData, msg ):
    data = msg.payload
    print("%s---%s"%(msg.topic,data))

    topics = msg.topic.split('/')
    
    module = topics[3]
    if module in _xmodules:
        return
   
    guid = topics[4]
    if guid in _xdevs:
        return 
    
    bodys = eval(data)['body']
    for body in bodys:
        serviceId = body['serviceId']
        if (len(_types)==0 or serviceId in _types) and serviceId not in _xtypes:
            print(u'%s--收到数据:%s'%(serviceId,body))
            if serviceId=="analog":
                for b in body['body']:
                    pass
                 
            elif serviceId=="event":
                for b in body['body']:
                    pass
                
            elif serviceId=="status":
                for b in body['body']:
                    pass
                
            elif serviceId=="file":
                for b in body['body']:
                    pass
            else:
                print(u"未知类型：%s"%serviceId)          
                
if __name__=='__main__':
    try:
        opts, args = getopt.getopt(sys.argv[1:],"ht:m:d:",["help","type=","xtype=","module=","xmodule=","dev=","xdev=","host=","port="])
    except getopt.GetoptError:
        print('%s -h查看帮助'%sys.argv[0])
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print(u'数据中心监视程序。')
            print('用法：%s [-t|--type|--xtype 类型1[,类型2[,...]]][-m|--module|--xmodule 模型1[,模型2[,...]][-d|--dev|--xdev 设备1[,设备2[,...]]'%sys.argv[0])
            print('用法：%s -h,--help'%sys.argv[0])
            print(u' -t,--type {类型列表}: 指定数据类型')            
            print(u' --xtype {类型列表}: 排除数据类型')
            print(u' -m,--module {模型列表}: 指定模型列表.注意，指定模型后，不应该再指定设备')
            print(u' --xmodule {模型列表}: 排除模型列表。模型建议使用"/模型1/,/模型2/"')
            print(u' -d,--dev {设备列表}: 指定设备列表。注意，指定设备后，不应该再指定模型')
            print(u' --xdev {设备列表}: 排除设备列表.设备列表建议使用"/设备1,/设备2"')
            print(u' --host {服务器主机}: 指定服务器主机名')
            print(u' --port {服务器端口}: 指定服务器端口。默认1338')
            print(u' -h,--help 显示本帮助信息')
            sys.exit()
        elif opt in ("-t", "--type"):
            _types = arg.split(',')
        elif opt=='--xtype':
            _xtypes = arg.split(',')
        elif opt in ("-m", "--module"):
            _modules = arg.split(',')
        elif opt=='--xmodule':
            _xmodules = arg.split(',')
        elif opt in ('-d','--dev'):
            _devs = arg.split(',')
        elif opt == '--xdev':
            _xdevs = arg.split(',')
        elif opt == '--host':
            _broker_address = arg
        elif opt == '--port':
            _broker_port = int(arg)
        else:
            print(u'未知参数%s:%s'%(opt,arg))
            
    if len(_broker_address)==0:
        print(u'请指定服务器地址')
        sys.exit(2)

    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_disconnect = on_disconn
    client.on_message = on_message

    client.connect(_broker_address, _broker_port, _broker_keepalive)
    client.loop_forever()